<template>
  <layout>
    <!-- 顶部操作 -->
    <section slot="search">
      <custom-form
        ref="search-form"
        class="search-form"
        v-model="tableSearch"
        layout="inline"
        mode="search"
        :FormList="searchColumns"
      >
        <a-button
          class="action-button"
          type="primary"
          @click="search()"
        >搜索</a-button>
        <a-button
          v-if="!isReadOnly"
          class="action-button"
          type="primary"
          auth="large-member.field-add"
          @click="handlerTableAdd()"
        >新增耕地信息</a-button>
        <a-button
          v-if="!isReadOnly"
          class="action-button"
          type="primary"
          auth="large-member.field-into"
          @click="handlerInto()"
        >转入耕地</a-button>
      </custom-form>
      <!-- <a-input placeholder="产品名称或者编号" v-model="tableSearch.searchKey" allowClear style="width: 200px;" /> -->
    </section>

    <!-- 产品列表 -->
    <a-table
      :dataSource="tableData"
      :columns="tableColumns"
      :rowKey="record => record.usr_id"
      :customRow="customTableRow"
      :loading="tableLoading"
      :pagination="false"
      :scroll="{
        x: '100%'
      }"
      bordered
    >
      <template
        slot="field_type"
        slot-scope="row"
      >
        {{getLabel(row.field_type, [], 'field_type')}}
      </template>
      <template
        slot="field_from"
        slot-scope="row"
      >
        {{getLabel(row.field_from, [], 'field_from')}}
      </template>

      <template
        slot="field_size"
        slot-scope="row"
      >
        {{(+row.field_from === 3 ? '-' : '') + row.field_size}}
      </template>
      
      <!-- 按钮区 -->
      <template
        slot="action"
        slot-scope="row"
      >
        <a-button
          class="action-button"
          type="link"
          v-if="!isReadOnly"
          size="small"
          auth="large-member.field-edit"
          @click="handleTableEdit(row)"
        >编辑</a-button>
        <a-popconfirm
          :title="`您确认要删除该条数据?`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="tableDel(row)"
        >
          <a-button
            class="action-button"
            type="link"
            auth="large-member.field-del"
            size="small"
          >删除</a-button>
          <!-- {{row.from_field ? "退回" : "删除"}} -->
        </a-popconfirm>
        <a-button
          class="action-button"
          type="link"
          v-if="!isReadOnly && +row.field_from !== 3"
          size="small"
          @click="handlerReduce(row)"
        >减少耕地</a-button>
      </template>
    </a-table>

    <!-- 产品列表分页器 -->
    <!-- <a-pagination
      slot="paging"
      :pageSizeOptions="pageSizes"
      :total="total"
      showSizeChanger
      :pageSize="pageSize"
      v-model="currentPage"
      @showSizeChange="changePageSize"
      @change="changePage"
    >
    </a-pagination> -->

    <!-- 编辑产品数据 -->
    <a-modal
      :visible="visible"
      :title="visibleTitle"
      centered
      @cancel="visible = false"
      @ok="customSubmit()"
    >
      <custom-form
        ref="custom-form"
        class="custom-form"
        v-model="currentRow"
        :FormList="formColumns"
        :mode="customMode"
        v-bind="formItemLayout"
        layout="horizontal"
      ></custom-form>
    </a-modal>

  </layout>
</template>

<script lang="ts">
import { Mixins, Component, Watch, Vue, Prop } from 'vue-property-decorator'
import { State, Mutation, Getter, namespace } from 'vuex-class'
import EventsMixin from '@/mixin/events'
import { TableMixin, AuthMixin } from '@/mixin'

import { TableLayout } from '@/layouts'
import CustomForm from '@/components/src/Form'
import { userServices, IAdmin } from '@/common/services'
import {
  largeMemberServices,
  ILargeMember,
  ILargePlant,
  ILargeField
} from '@/common/services/largeMember'
import { commonServices } from '@/common/services/common'
import { memberRole } from '@/common/enum'
import { publishServices } from '@/common/services/publish';
import Into from './Into.vue'
import { publicServices } from '@/common/services/public'

@Component({
  components: {
    Layout: TableLayout,
    Into,
    CustomForm
  }
})
export default class AdminList extends Mixins(
  EventsMixin,
  TableMixin,
  AuthMixin
) {
  @Prop({
    type: Object
  })
  public currentField!: ILargeMember
  @Prop({
    type: Number
  })
  public currentFieldType!: number

  @Prop({
    type: Boolean
  })
  public isReadOnly!: boolean
  @Prop({
    type: String
  })
  public currentPublishId!: string

  public commonParams = {
    s_a_id: '',
    big_mb_id: '',
    pub_id: this.currentPublishId
  }

  // 产品列表搜索条件
  public tableSearch = {
    field_from: ''
  }

  public formItemLayout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 17 }
  }

  // 自定义mode
  public customMode = ''

  // 默认配置
  get defaultCurrentArea () {
    return {
      s_a_id: this.currentField.s_a_id,
      s_a_nam: this.currentField.s_a_nam,
      selectable: this.currentField.s_a_id.length === 14
    }
  }

  // 产品列表表格信息
  public columns: ITable.IColumn[] = [
    {
      title: '记录号',
      key: 'field_id',
      dataIndex: 'field_id',
      width: 120,
    },
    {
      title: '大户耕地编号',
      key: 'field_id2',
      dataIndex: 'field_id2',
      width: 120,
    },
    {
      title: '耕地类型',
      scopedSlots: { customRender: 'field_type' },
      key: 'field_type',
      width: 80,
      form: {
        type: 'a-radio-group',
        validate: '*',
        isShowQuery: true,
        renderMode: ['add', 'edit'],
        disabled: ['edit'],
        placeholder: '请选择耕地类型',
        dict: [
          {
            label: '田',
            value: '1'
          },
          {
            label: '土',
            value: '2'
          }
        ]
      }
    },

    {
      title: '耕地所属行政区',
      key: 's_a_id',
      width: 200,
      scopedSlots: { customRender: 's_a_id' },
      form: {
        type: 'a-tree-select',
        placeholder: '请选择所属行政地区到（社/组）一级',
        // treeDataSimpleMode: true,
        treeData: [
          this.defaultCurrentArea
        ],
        disabled: ['edit'],
        renderMode: ['add', 'edit'],
        tips: '请选择所属行政地区到（社/组）一级',
        // showSearch: true,
        treeNodeFilterProp: 'title',
        loadData: this.onLoadData,
        dropdownStyle: {
          'overflow-y': 'scroll',
          maxHeight: "600px"
        },
        validate: '*',
        isShowList: false,
        replaceFields: { title: 's_a_nam', key: 's_a_id', value: 's_a_id', children: 'children' },
        handler: {
          change: () => {
            // this.getPro
          }
        }
      }
    },

    {
      title: '耕地所属行政区',
      key: 's_a_nam_all',
      width: 200,
      dataIndex: 's_a_nam_all',
      form: {
        isShowFrom: false,
      }
    },

    // 列表专用
    {
      title: '耕地性质',
      scopedSlots: { customRender: 'field_from' },
      key: 'field_from',
      width: 80,
      form: {
        type: 'a-radio-group',
        isShowQuery: true,
        isShowFrom: false,
        dict: [
          {
            label: '承包地',
            value: '1'
          },
          {
            label: '增加面积',
            value: '2'
          },
          {
            label: '减少面积',
            value: '3'
          }
        ]
      }
    },


    {
      title: '耕地性质',
      scopedSlots: { customRender: 'field_from' },
      key: 'field_from',
      width: 80,
      form: {
        type: 'a-radio-group',
        isShowList: false,
        disabled: ['edit'],
        renderMode: ['add', 'edit'],
        dict: [
          {
            label: '承包地',
            value: '1'
          },
          {
            label: '增加面积',
            value: '2'
          }
        ]
      }
    },
    {
      title: '确权面积（亩）',
      // dataIndex: 'field_size',
      scopedSlots: { customRender: 'field_size' },
      key: 'field_size',
      width: 120,
      align: 'right',
      form: {
        type: 'a-input',
        disabled: ['edit'],
        placeholder: '请输入确权面积',
        renderMode: ['add', 'edit'],
        validate: '*',
      }
    },
    {
      title: '地理位置（经度）',
      dataIndex: 'field_long',
      key: 'field_long',
      width: 150,
      form: {
        type: 'a-input',
        placeholder: '请输入经度',
        renderMode: ['add', 'edit']
      }
    },
    {
      title: '地理位置（纬度）',
      dataIndex: 'field_law',
      key: 'field_law',
      width: 150,
      form: {
        type: 'a-input',
        placeholder: '请输入纬度',
        renderMode: ['add', 'edit']
      }
    },
    {
      title: '耕地来源或去向',
      dataIndex: 'readme_sys',
      key: 'readme_sys',
      width: 200,
      form: {
        type: 'a-input',
        placeholder: '',
        isShowFrom: false
      }
    },
    // {
    //   title: '接收人',
    //   dataIndex: 'readme',
    //   key: 'readme',
    //   form: {
    //     type: 'a-input',
    //     placeholder: ''
    //   }
    // },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      ellipsis: true,
      form: {
        type: 'a-textarea',
        placeholder: '请输入备注',
        renderMode: ['add', 'edit']
      }
    },

    // 减少专用
    {
      title: '确权面积（亩）',
      dataIndex: 'field_size',
      key: 'field_size',
      width: 120,
      align: 'right',
      form: {
        type: 'a-input',
        placeholder: '输入减少的确权面积',
        isShowList: false,
        renderMode: ['del']
      }
    },
    {
      title: '备注',
      dataIndex: 'readme',
      key: 'readme',
      form: {
        type: 'a-textarea',
        placeholder: '输入减少面积的原因',
        isShowList: false,
        renderMode: ['del']
      }
    },
    {
      title: '操作',
      key: 'action',
      width: 160,
      fixed: 'right',
      form: {
        isShowList: !this.isReadOnly,
        isShowFrom: false
      },
      scopedSlots: { customRender: 'action' }
    }
  ]

  public tableApi = {
    list: this.currentPublishId ? publishServices.getPublishLargeFields : largeMemberServices.getLargeMemberFields,
    add: largeMemberServices.updateLargeMemberField,
    edit: largeMemberServices.updateLargeMemberField,
    del: largeMemberServices.deleteLargeMemberField,
    // imageUpload: 'uploadStoreImage',
    // imageRemove: 'delStoreImage'
  }

  @Watch('currentField.big_mb_id', { immediate: true })
  @Watch('currentFieldType', { immediate: true })
  public handlerCurrentFieldChange() {
    this.commonParams.s_a_id = this.currentField.s_a_id
    this.commonParams.big_mb_id = this.currentField.big_mb_id
    this.tableSearch.field_from = `${this.currentFieldType}`
    this.resetAreaData()
    this.getData()
  }

  public mounted() {
    this.handlerAddGrainColumn()
  }

  public handlerAddGrainColumn() {
    const grains = [
      '水稻',
      '玉米',
      '小麦',
      '红苕',
      '马铃薯',
      '大豆',
      '绿豆',
      '豌葫豆',
      '高粱',
      '荞麦',
      '肾豆',
      '红小豆'
    ]
    const grainsColumns = grains.map((item, index) => {
      const key = 'plant' + (index + 1)
      return {
        title: item,
        dataIndex: key,
        key,
        form: {
          type: 'a-input',
          placeholder: `请输入${item}面积`,
          renderMode: ['grain'],
          isShowList: false
        }
      }
    })
    this.columns = this.columns.concat(grainsColumns)
  }

  public async getData() {
    const res = await this.getTableList()
    this.tableData = res.data || []
  }

  public handlerTableAdd() {
    this.tableAdd()
    this.customMode = 'add'
    this.visibleTitle = '添加耕地'
    this.$nextTick(() => {
      this.currentRow = Object.assign({}, {
        s_a_id: undefined,
        field_from: `${this.currentFieldType}`
      })
    })
  }

  // 编辑前数据预处理
  public async handleTableEdit(row: ILargePlant) {
    this.customMode = 'edit'
    this.tableEdit(Object.assign({}, row, {
      s_a_id: row.s_a_nam_all,
      _s_a_id: row.s_a_id
    }))
    this.visibleTitle = "修改"
  }

  public async onLoadData(treeNode?: any) {
    const res = await publicServices.getAreaLazy({
      s_a_id: treeNode ? treeNode.dataRef.s_a_id : this.currentField.s_a_id || '0'
    })
    // 判断是否是叶子节点
    const treeData = res.data.map(item => {
      if (item.s_a_id.length === 14) {
        // @ts-ignore
        item.isLeaf = true
      } else {
        // @ts-ignore
        item.selectable = false
      }
      return item
    })
    if (!treeNode) {
      this.changeDict('s_a_id', treeData, 'treeData')
    } else {
      treeNode.dataRef.children = treeData
      const currentTreeData = this.columns.find((column) => {
        return 's_a_id' === column.key && column.form;
      })
      this.changeDict('s_a_id', [...(currentTreeData?.form?.treeData || [])], 'treeData')
    }
  }

  // 刷新行政区划树数据
  public refreshAreaData() {
    const currentTreeData = this.columns.find((column) => {
      return 's_a_id' === column.key && column.form;
    })
    this.changeDict('s_a_id', [...(currentTreeData?.form?.treeData || [])], 'treeData')
  }
  // 重置行政区划树数据
  public resetAreaData() {
    this.columns.find((column) => {
      if ('s_a_id' === column.key) {
        // @ts-ignore
        column.form.treeData = [this.defaultCurrentArea]
      }
    })
  }

  // 转入耕地
  public handlerInto() {
    this.$dialog(Into, {
      record: {
      },
      currentAreaId: this.currentField.s_a_id,
      currentMemberId: this.currentField.big_mb_id,
      currentAreaName: this.currentField.s_a_nam,
      on: {
        ok () {
        },
        cancel () {
          console.log('cancel 回调')
        },
        close () {
          console.log('modal close 回调')
        }
      }
    },
    // modal props
    {
      title: '填写土地出让信息（大户种粮地点：' + this.currentField.s_a_nam_all + ")",
      width: '80%',
      centered: true,
      maskClosable: false,
      footer: null
    })
  }

  // 自定义提交
  public customSubmit() {
    this.handleSubmit({}, true, (params: any) => {
      if (params.s_a_id === params.s_a_nam) {
        params.s_a_id = params._s_a_id
      }
      return params
    })
  }

  public handlerReduce(row: ILargeField) {
    this.visible = true
    this.visibleTitle = '减少耕地（登记用于建房、修路等减少面积）'
    this.formMode = 'edit'
    this.customMode = 'del'
    this.$nextTick(() => {
      this.$refs['custom-form'].resetFields()
      this.currentRow = {
        field_type: row.field_type,
        field_from: '3',
        field_id2: row.field_id,
        field_long: row.field_long,
        field_law: row.field_law,
        readme: '',
        field_size: ''
      }
    })
  }
}
</script>

<style scoped>
.action-button {
  margin: 0px 10px 0px 10px;
}
.form-item-class {
  margin-bottom: 0px;
}
.img-box {
  width: 100px;
  height: 100px;
  margin: 10px;
}
.item-blue {
  color: #1989fa;
}
</style>
